<template>
  <div class="app-container">
    <!-- 原有内容保持不变 -->
    <el-card title="预警接收人管理">
      <!-- 操作按钮区域 -->
      <div class="table-operations">
        <el-button type="primary" icon="el-icon-plus" @click="handleAdd">
          添加接收人
        </el-button>
        <el-button type="success" icon="el-icon-upload" @click="showImportDialog">
          导入接收人
        </el-button>
        <el-button type="success" icon="el-icon-download" @click="handleExport">
          导出接收人列表
        </el-button>
        <el-input
          v-model="searchQuery"
          placeholder="输入姓名搜索"
          style="width: 240px; margin-left: 10px"
          prefix-icon="el-icon-search"
        />
      </div>

      <!-- 接收人表格 -->
      <el-table
        :data="recipientList"
        border
        stripe
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="recipientId" label="ID" width="80"></el-table-column>
        <el-table-column label="头像" width="100">
          <template slot-scope="scope">
            <el-image
              :src="scope.row.recipientAvatarUrl"
              alt="头像"
              style="width: 40px; height: 40px; border-radius: 50%; cursor: pointer;"
              @click="showUserDetail(scope.row)"
            ></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="recipientName" label="姓名" width="120"></el-table-column>
        <el-table-column prop="recipientEmail" label="邮箱" width="200"></el-table-column>
        <el-table-column prop="recipientPhone" label="电话" width="150"></el-table-column>
        <el-table-column prop="recipientProductCategory" label="产品分类" width="150"></el-table-column>
        <el-table-column prop="recipientRemarks" label="备注" width="200" show-overflow-tooltip></el-table-column>
        <el-table-column label="操作" width="200" align="center">
          <template slot-scope="scope">
            <el-button type="text" icon="el-icon-edit" @click="handleEdit(scope.row)">
              编辑
            </el-button>
            <el-button type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                       style="color: #f56c6c">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页控件 -->
      <div class="pagination-container">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          :current-page="currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </el-card>

    <!-- 添加/编辑接收人弹窗 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px">
      <el-form ref="recipientForm" :model="form" :rules="rules" label-width="100px">
        <!-- 接收人名称 -->
        <el-form-item label="接收人名称" prop="recipientName">
          <el-input v-model="form.recipientName" placeholder="请输入接收人名称"></el-input>
        </el-form-item>

        <!-- 头像：修改为打开裁剪弹窗 -->
        <el-form-item label="头像">
          <div class="avatar-uploader">
            <img v-if="form.recipientAvatarUrl" :src="form.recipientAvatarUrl" class="avatar" @click="openCropperDialog">
            <i v-else class="el-icon-plus avatar-uploader-icon" @click="openCropperDialog"></i>
          </div>
        </el-form-item>

        <!-- 邮箱 -->
        <el-form-item label="邮箱" prop="recipientEmail">
          <el-input v-model="form.recipientEmail" placeholder="请输入邮箱"></el-input>
        </el-form-item>

        <!-- 手机号 -->
        <el-form-item label="手机号" prop="recipientPhone">
          <el-input v-model="form.recipientPhone" placeholder="请输入手机号"></el-input>
        </el-form-item>

        <!-- 产品分类 -->
        <el-form-item label="产品分类" prop="recipientProductCategory">
          <el-input
            v-model.number="form.recipientProductCategory"
            placeholder="请输入产品分类数字"
            type="number"
          ></el-input>
        </el-form-item>

        <!-- 备注 -->
        <el-form-item label="备注" prop="recipientRemarks">
          <el-input
            v-model="form.recipientRemarks"
            placeholder="请输入备注信息"
            type="textarea"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>


    <!-- 导入弹窗 -->
    <el-dialog
      title="导入接收人"
      :visible.sync="importDialogVisible"
      width="500px"
      top="15vh"
      append-to-body
    >
      <div style="padding: 20px 0">
        <el-upload
          ref="upload"
          :auto-upload="false"
          :on-change="handleFileChange"
          :file-list="fileList"
          accept=".xlsx, .xls"
          :limit="1"
          :before-upload="beforeUpload"
          action="#"
          class="upload-demo"
        >
          <el-button slot="trigger" size="small" type="primary">选择Excel文件</el-button>
          <div slot="tip" class="el-upload__tip">
            只能上传xlsx、xls文件，且不超过2MB
          </div>
        </el-upload>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleDownloadTemplate">下载模板</el-button>
        <el-button @click="cancelImport">取消</el-button>
        <el-button type="primary" @click="handleImport">确认导入</el-button>
      </div>
    </el-dialog>


    <!-- 添加图片裁剪弹窗 -->
    <el-dialog title="裁剪头像" :visible.sync="cropperDialogVisible" width="800px" append-to-body @opened="modalOpened" @close="closeCropperDialog">
      <el-row>
        <el-col :xs="24" :md="12" :style="{height: '350px'}">
          <vue-cropper
            ref="cropper"
            :img="options.img"
            :info="true"
            :autoCrop="options.autoCrop"
            :autoCropWidth="options.autoCropWidth"
            :autoCropHeight="options.autoCropHeight"
            :fixedBox="options.fixedBox"
            :outputType="options.outputType"
            @realTime="realTime"
            v-if="visible"
          />
        </el-col>
        <el-col :xs="24" :md="12" :style="{height: '350px'}">
          <!-- 只保留一个预览框，直接显示裁剪内容 -->
          <div class="avatar-upload-preview">
            <img v-if="options.img" :src="options.img" style="max-width: 100%; max-height: 100%;" />
            <div v-else class="preview-placeholder">请选择图片进行裁剪预览</div>
          </div>
        </el-col>
      </el-row>
      <br />
      <el-row>
        <el-col :lg="2" :sm="3" :xs="3">
          <el-upload action="#" :http-request="requestUpload" :show-file-list="false" :before-upload="beforeAvatarUpload">
            <el-button size="small">
              选择图片
              <i class="el-icon-upload el-icon--right"></i>
            </el-button>
          </el-upload>
        </el-col>
        <el-col :lg="{span: 1, offset: 2}" :sm="2" :xs="2">
          <el-button icon="el-icon-plus" size="small" @click="changeScale(1)"></el-button>
        </el-col>
        <el-col :lg="{span: 1, offset: 1}" :sm="2" :xs="2">
          <el-button icon="el-icon-minus" size="small" @click="changeScale(-1)"></el-button>
        </el-col>
        <el-col :lg="{span: 1, offset: 1}" :sm="2" :xs="2">
          <el-button icon="el-icon-refresh-left" size="small" @click="rotateLeft()"></el-button>
        </el-col>
        <el-col :lg="{span: 1, offset: 1}" :sm="2" :xs="2">
          <el-button icon="el-icon-refresh-right" size="small" @click="rotateRight()"></el-button>
        </el-col>
        <el-col :lg="{span: 2, offset: 6}" :sm="2" :xs="2">
          <el-button type="primary" size="small" @click="uploadCroppedImg()">提 交</el-button>
        </el-col>
      </el-row>
    </el-dialog>
    <!-- 用户详情弹窗 - 新增的弹窗 -->
    <el-dialog title="用户详情" :visible.sync="detailDialogVisible" width="400px">
      <!-- 新增v-if：避免selectedUser为null时读取属性报错 -->
      <div class="user-detail-container" v-if="selectedUser">
        <div class="avatar-large-container">
          <img
            v-if="selectedUser.recipientAvatarUrl"
            :src="selectedUser.recipientAvatarUrl"
            alt="用户头像"
            class="avatar-large"
          >
          <div v-else class="avatar-placeholder">
            <i class="el-icon-user"></i>
          </div>
        </div>
        <div class="user-info">
          <el-descriptions :column="1" border>
            <el-descriptions-item label="姓名">{{ selectedUser.recipientName }}</el-descriptions-item>
            <el-descriptions-item label="邮箱">{{ selectedUser.recipientEmail }}</el-descriptions-item>
            <el-descriptions-item label="电话">{{ selectedUser.recipientPhone }}</el-descriptions-item>
            <el-descriptions-item label="产品分类">{{ selectedUser.recipientProductCategory }}</el-descriptions-item>
            <el-descriptions-item label="备注" v-if="selectedUser.recipientRemarks">{{ selectedUser.recipientRemarks }}</el-descriptions-item>
            <el-descriptions-item label="备注" v-else>无</el-descriptions-item>
          </el-descriptions>
        </div>
      </div>
    </el-dialog>
  </div>
</template>


<script>
import recipientApi from '@/api/warn/recipient'
import { VueCropper } from 'vue-cropper'
import { debounce } from '@/utils'

export default {
  name: 'RecipientList',
  components: { VueCropper },
  data() {
    return {
      recipientList: [],
      total: 0,
      pageSize: 10,
      currentPage: 1,
      searchQuery: '',
      dialogVisible: false,
      dialogTitle: '',
      // 新增：用户详情弹窗相关 - 初始值改为null，避免隐性报错
      detailDialogVisible: false,
      selectedUser: null, // 修复：从{}改为null
      // 导入相关数据
      importDialogVisible: false,
      fileList: [],
      uploadFile: null,
      // 表单字段：统一带recipient前缀
      form: {
        recipientId: '',
        recipientName: '',
        recipientEmail: '',
        recipientPhone: '',
        // 修复：数字类型初始值改为null（匹配v-model.number）
        recipientProductCategory: null,
        recipientRemarks: '',
        recipientAvatarUrl: ''
      },
      // 验证规则
      rules: {
        recipientName: [
          { required: true, message: '请输入接收人名称', trigger: 'blur' }
        ],
        recipientEmail: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
        ],
        recipientPhone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
        ],
        recipientProductCategory: [
          { required: true, message: '请输入产品分类数字', trigger: 'blur' },
          { type: 'number', message: '请输入有效的数字', trigger: 'blur' }
        ]
      },
      multipleSelection: [],
      searchTimer: null,

      // 图片裁剪相关配置
      cropperDialogVisible: false,
      visible: false,
      options: {
        img: '',
        autoCrop: true,
        autoCropWidth: 200,
        autoCropHeight: 200,
        fixedBox: true,
        outputType: 'png',
        filename: 'avatar'
      },
      previews: { url: '', img: {} },
      resizeHandler: null
    }
  },
  created() {
    this.loadRecipientList()
  },
  methods: {
    // 显示导入弹窗
    showImportDialog() {
      this.importDialogVisible = true
      this.fileList = []
      this.uploadFile = null
    },

    // 文件改变时触发
    handleFileChange(file, fileList) {
      this.uploadFile = file.raw
    },

    // 上传前校验
    beforeUpload(file) {
      const isExcel = file.type === 'application/vnd.ms-excel' || file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isExcel) {
        this.$message.error('只能上传Excel文件!')
        return false
      }
      if (!isLt2M) {
        this.$message.error('文件大小不能超过2MB!')
        return false
      }
      return isExcel && isLt2M
    },

    // 下载模板
    handleDownloadTemplate() {
      this.$confirm('确定要下载Excel模板吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }).then(() => {
        recipientApi.downloadTemplate()
          .then(response => {
            const blob = new Blob([response], {
              type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
            })
            const url = URL.createObjectURL(blob)
            const a = document.createElement('a')
            a.href = url
            const fileName = '预警接收人导入模板.xlsx'
            a.download = fileName
            a.click()
            URL.revokeObjectURL(url)
            this.$message.success('模板下载成功')
          })
          .catch(error => {
            console.error('下载模板失败', error)
            this.$message.error('模板下载失败，请重试')
          })
      }).catch(() => {
        this.$message.info('已取消下载')
      })
    },

    // 取消导入
    cancelImport() {
      this.importDialogVisible = false
      this.fileList = []
      this.uploadFile = null
    },

    // 确认导入
    handleImport() {
      console.log('开始导入，uploadFile:', this.uploadFile)
      if (!this.uploadFile) {
        this.$message.warning('请选择要导入的Excel文件')
        return
      }

      this.$confirm('确定要导入这些数据吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        console.log('用户确认导入')
        this.$modal.loading("正在导入数据，请稍候！")
        recipientApi.importRecipient(this.uploadFile).then(res => {
          console.log('导入API返回结果:', res)
          this.$modal.closeLoading()
          if (res.code === 200) {
            this.$message.success('导入成功')
            this.importDialogVisible = false
            this.loadRecipientList() // 重新加载列表
          } else {
            this.$message.error(res.msg || '导入失败')
          }
        }).catch(err => {
          console.error('导入API调用失败:', err)
          this.$modal.closeLoading()
          this.$message.error('导入失败：' + (err.message || '未知错误'))
        })
      }).catch(error => {
        console.log('确认对话框被取消:', error)
        this.$message.info('已取消导入')
      })
    },
    // 原有方法保持不变
    loadRecipientList() {
      recipientApi.getRecipientList({
        pageNum: this.currentPage,
        pageSize: this.pageSize,
        recipientName: this.searchQuery
      }).then(response => {
        this.recipientList = response.data.list
        this.total = response.data.total
      }).catch(error => {
        this.$message.error('加载接收人列表失败: ' + (error.message || '网络异常'))
      })
    },
    // 修复：保留一个showUserDetail方法，删除外部重复定义
    showUserDetail(user) {
      this.selectedUser = { ...user } // 深拷贝用户数据
      this.detailDialogVisible = true // 打开弹窗
    },
    // 修复：将所有方法移到methods内部
    handleSearch() {
      this.currentPage = 1
      this.loadRecipientList()
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.loadRecipientList()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.loadRecipientList()
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleAdd() {
      this.dialogTitle = '添加预警接收人'
      // 重置整个表单对象
      this.form = {
        recipientId: null,
        recipientName: '',
        recipientEmail: '',
        recipientPhone: '',
        recipientProductCategory: null, // 同步改为null
        recipientRemarks: '',
        recipientAvatarUrl: ''
      }
      this.$refs.recipientForm && this.$refs.recipientForm.clearValidate()
      this.dialogVisible = true
    },
    handleEdit(row) {
      this.dialogTitle = '编辑预警接收人'
      this.$refs.recipientForm && this.$refs.recipientForm.clearValidate()
      this.form = {...row}
      this.dialogVisible = true
    },
    submitForm() {
      this.$refs.recipientForm.validate(async (valid) => {
        if (valid) {
          try {
            if (this.form.recipientId) {
              await recipientApi.updateRecipient(this.form)
              this.$message.success('修改成功')
            } else {
              await recipientApi.addRecipient(this.form)
              this.$message.success('新增成功')
            }
            this.dialogVisible = false
            this.loadRecipientList()
          } catch (error) {
            this.$message.error(error.msg || '操作失败，请重试')
          }
        }
      })
    },
    handleDelete(row) {
      this.$confirm(`确定要删除 ${row.recipientName} 吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        recipientApi.deleteRecipient(row.recipientId)
          .then(() => {
            this.$message.success('删除成功')
            this.loadRecipientList()
          })
          .catch(error => {
            this.$message.error('删除失败: ' + (error.message || '网络异常'))
          })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    handleExport() {
      recipientApi.exportRecipient()
        .then(response => {
          const blob = new Blob([response], {
            type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
          })
          const url = URL.createObjectURL(blob)
          const a = document.createElement('a')
          a.href = url
          const date = new Date()
          const year = date.getFullYear()
          const month = String(date.getMonth() + 1).padStart(2, '0')
          const day = String(date.getDate()).padStart(2, '0')
          const fileName = `预警接收人列表_${year}${month}${day}.xlsx`
          a.download = fileName
          a.click()
          URL.revokeObjectURL(url)
          this.$message.success('导出成功')
        })
        .catch(error => {
          this.$message.error('导出失败: ' + (error.message || '网络异常'))
        })
    },
    // 打开裁剪弹窗
    openCropperDialog() {
      this.options.img = this.form.recipientAvatarUrl || ''
      this.cropperDialogVisible = true
    },
    // 打开弹出层结束时的回调
    modalOpened() {
      this.visible = true
      if (!this.resizeHandler) {
        this.resizeHandler = debounce(() => {
          this.refresh()
        }, 100)
      }
      window.addEventListener('resize', this.resizeHandler)
    },
    // 刷新裁剪组件
    refresh() {
      this.$refs.cropper.refresh()
    },
    // 覆盖默认的上传行为
    requestUpload() {},
    // 向左旋转
    rotateLeft() {
      this.$refs.cropper.rotateLeft()
    },
    // 向右旋转
    rotateRight() {
      this.$refs.cropper.rotateRight()
    },
    // 图片缩放
    changeScale(num) {
      num = num || 1
      this.$refs.cropper.changeScale(num)
    },
    // 头像上传前校验
    beforeAvatarUpload(file) {
      const isImage = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isImage) {
        this.$message.error('上传头像只能是 JPG 或 PNG 格式!')
        return false
      }
      if (!isLt2M) {
        this.$message.error('上传头像大小不能超过 2MB!')
        return false
      }

      const reader = new FileReader()
      reader.readAsDataURL(file)
      reader.onload = () => {
        this.options.img = reader.result
        this.options.filename = file.name
      }
      return false // 阻止默认上传
    },
    // 上传裁剪后的图片
    uploadCroppedImg() {
      this.$refs.cropper.getCropBlob(data => {
        const fileName = 'avatar_' + Date.now() + '.png';
        const file = new File([data], fileName, { type: 'image/png' });

        recipientApi.uploadAvatar(file)
          .then(response => {
            this.form.recipientAvatarUrl = response.data.url
            this.cropperDialogVisible = false
            this.visible = false
            this.$message.success('头像上传成功')
          })
          .catch(error => {
            this.$message.error('头像上传失败: ' + (error.message || '网络异常'))
          })
      })
    },
    // 实时预览方法改进
    realTime(data) {
      console.log('预览更新', data);
    },
    // 修复：闭合方法的大括号
    closeCropperDialog() {
      this.visible = false
      window.removeEventListener('resize', this.resizeHandler)
    }
  },
  // 搜索防抖（watch与methods同级，位置正确）
  watch: {
    searchQuery(val) {
      clearTimeout(this.searchTimer)
      this.searchTimer = setTimeout(() => {
        this.handleSearch()
      }, 500)
    }
  },
  // 组件销毁时清除定时器
  beforeDestroy() {
    clearTimeout(this.searchTimer)
    window.removeEventListener('resize', this.resizeHandler)
  }
}
</script>

<style scoped>
/* 样式部分保持不变 */
.table-operations {
  margin-bottom: 16px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.pagination-container {
  margin-top: 16px;
  text-align: right;
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
  width: 178px;
  height: 178px;
}

.avatar-uploader:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
  border-radius: 4px;
}

.avatar-upload-preview {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  width: 100%;
  background-color: #f5f5f5;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  overflow: hidden;
}

.avatar-upload-preview img {
  display: block;
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

.preview-placeholder {
  color: #999;
  font-size: 14px;
  text-align: center;
}

/* 新增：用户详情弹窗样式 */
.user-detail-container {
  padding: 20px;
}

.avatar-large-container {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}

.avatar-large {
  width: 150px;
  height: 150px;
  border-radius: 50%;
  object-fit: cover;
}

.avatar-placeholder {
  width: 150px;
  height: 150px;
  border-radius: 50%;
  background-color: #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 50px;
  color: #ccc;
}

.user-info {
  margin-top: 20px;
}
</style>
